package softtech.apps.callblocker.adapter;

import java.util.ArrayList;
import java.util.List;

import softtech.apps.utility.ViewAlertDialogManager;
import softtech.apps.callblocker.ActivityCallSetting;
import softtech.apps.callblocker.ActivityChat;
import softtech.apps.callblocker.ActivityContactProfile;
import softtech.apps.callblocker.ActivityShowBlackListItem;
import softtech.apps.callblocker.ActivityTest;
import softtech.apps.callblocker.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.sax.StartElementListener;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.Toast;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView;
import softtech.apps.callblocker.model.BlackListItem;
import softtech.apps.callblocker.model.DatabaseHanler;
import softtech.apps.callblocker.quickAction.ActionItem;
import softtech.apps.callblocker.quickAction.ActionItem1;
import softtech.apps.callblocker.quickAction.QuickAction;
import softtech.apps.callblocker.quickAction.QuickAction1;
import softtech.apps.callblocker.quickAction.QuickAction1.OnActionItem1ClickListener;

public class AdapterBlackList extends BaseAdapter {

	private static final int ID_CALL = 1;
	private static final int ID_SMS = 2;
	private static final int ID_SETTING = 3;
	private static final int ID_INFO = 4;
	private static final int ID_DELETE = 5;
	private static final String TAG = null;

	private DatabaseHanler db;
	private Activity activity;
	private LayoutInflater inflater;
	private List<BlackListItem> blackListItem = new ArrayList<BlackListItem>();
	private BlackListItem item;
	private BlackListItem itemTemp;
	QuickAction1 mQuickAction;
	public int count = 40;

	public AdapterBlackList(Activity activity, List<BlackListItem> list) {
		this.activity = activity;
		this.blackListItem = list;
		db = new DatabaseHanler(activity);
	}

	public void setCount(int count) {
		this.count += count;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		if (blackListItem == null || blackListItem.equals(null)
				|| blackListItem.size() == 0) {
			return 0;
		}
		if (blackListItem.size() < 40) {
			return blackListItem.size();
		}
		return Math.min(blackListItem.size(), this.count);
	}

	public void update(List<BlackListItem> list) {
		this.count += 1;
		blackListItem = list;
		notifyDataSetChanged();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return blackListItem.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@SuppressWarnings("deprecation")
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub

		if (inflater == null) {
			inflater = (LayoutInflater) activity
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		}
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.item_blacklist, null);

		}
		item = blackListItem.get(position);

		TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
		TextView tvPhoneNumber = (TextView) convertView
				.findViewById(R.id.tvPhoneNumber);
		ImageView img = (ImageView) convertView.findViewById(R.id.imgView);
		ImageView imgCallMode = (ImageView) convertView
				.findViewById(R.id.imgCallMode);

		img.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				View someView = activity.findViewById(R.id.layoutShowBlackList);
				// someView.setBackgroundColor(Color.parseColor("#1e1f24"));
				showQuickAction(activity, v, item, position);
			}
		});

		tvName.setText(item.getName());
		tvPhoneNumber.setText(item.getPhoneNumber());

		if (item.getName().equals(null) || item.getName().equals("")) {
			tvName.setVisibility(View.GONE);
			tvPhoneNumber.setGravity(Gravity.CENTER_VERTICAL);
		} else {
			tvName.setVisibility(View.VISIBLE);
			tvName.setText(item.getName());
			tvPhoneNumber.setText(item.getPhoneNumber());
			tvPhoneNumber.setGravity(Gravity.NO_GRAVITY);
		}
		int modeCall = (item.getMode() & 240) >> 4;
		switch (modeCall) {
		case 1:
			imgCallMode.setImageResource(R.drawable.modecall1);
			break;
		case 2:
			imgCallMode.setImageResource(R.drawable.modecall1);
			break;
		case 3:
			imgCallMode.setImageResource(R.drawable.modecall3);
			break;
		case 4:
			imgCallMode.setImageResource(R.drawable.modecall3);
			break;
		case 5:
			imgCallMode.setImageResource(R.drawable.modecall5);
			break;
		case 6:
			imgCallMode.setImageResource(R.drawable.modecall5);
			break;
		default:
			break;
		}

		return convertView;
	}

	public void showQuickAction(Context context, View v,
			final BlackListItem item, final int position) {
		ActionItem1 callItem = new ActionItem1(ID_CALL, activity.getResources()
				.getString(R.string.call), activity.getResources().getDrawable(
				R.drawable.call));
		
		ActionItem1 smsItem = new ActionItem1(ID_SMS, activity.getResources()
				.getString(R.string.sms), activity.getResources().getDrawable(
				R.drawable.smsquick));
		
		ActionItem1 settingItem = new ActionItem1(ID_SETTING, activity
				.getResources().getString(R.string.setting_mode), activity
				.getResources().getDrawable(R.drawable.settingmode));
		
		ActionItem1 infoItem = new ActionItem1(ID_INFO, activity.getResources()
				.getString(R.string.view_profile), activity.getResources()
				.getDrawable(R.drawable.viewprofile));
		
		ActionItem1 deleteItem = new ActionItem1(ID_DELETE, activity
				.getResources().getString(R.string.delete), activity
				.getResources().getDrawable(R.drawable.deleteitem));
		deleteItem.set_is_last(true);
		// add action items into QuickAction
		mQuickAction = new QuickAction1(activity, 1);
		mQuickAction.addActionItem1(callItem);
		mQuickAction.addActionItem1(smsItem);
		mQuickAction.addActionItem1(settingItem);
		mQuickAction.addActionItem1(infoItem);
		mQuickAction.addActionItem1(deleteItem);
		

		mQuickAction
				.setOnActionItem1ClickListener(new OnActionItem1ClickListener() {

					@Override
					public void onItemClick(QuickAction1 source, int pos,
							int actionId) {
						// TODO Auto-generated method stub
						ActionItem1 actionItem = mQuickAction
								.getActionItem1(pos);

						// here we can filter which action item was clicked with
						// pos or actionId parameter
						if (actionId == ID_CALL) {
							itemTemp = blackListItem.get(position);
							showAlertDialog(
									activity.getResources().getString(
											R.string.title_alert_dialog1),
									activity.getResources().getString(
											R.string.message_alert_dialog1),
									itemTemp.getPhoneNumber(), 1);
						} else if (actionId == ID_SMS) {
							itemTemp = blackListItem.get(position);
							showAlertDialog(
									activity.getResources().getString(
											R.string.title_alert_dialog1),
									activity.getResources().getString(
											R.string.message_alert_dialog2),
									itemTemp.getPhoneNumber(), 2);
						} else if (actionId == ID_SETTING) {

							itemTemp = blackListItem.get(position);
							final Dialog dialog = new Dialog(activity);
							dialog.setContentView(R.layout.dialog_call_mode);
							dialog.setTitle(activity.getResources().getString(
									R.string.title_dialog_add_phone));

							ListView lvCallSetting = (ListView) dialog
									.findViewById(R.id.lvModeCallInDialog);
							AdapterCallModeDialog adapter = new AdapterCallModeDialog(
									activity, itemTemp.getMode());
							lvCallSetting.setAdapter(adapter);
							lvCallSetting
									.setOnItemClickListener(new OnItemClickListener() {

										@Override
										public void onItemClick(
												AdapterView<?> parent,
												View view, int position, long id) {
											// TODO Auto-generated method stub
											int modeSms = itemTemp.getMode() & 15;
											itemTemp.setMode((itemTemp
													.getMode() & 15)
													| ((position + 1) << 4));
											Log.i(TAG,
													"modemoi: "
															+ itemTemp
																	.getMode());
											db.updateBlackListItem(itemTemp,
													BlackListItem.ID + " = "
															+ itemTemp.getId(),
													null);
											blackListItem = db
													.getBlackListItem(null,
															null, null, null,
															null);
											update(blackListItem);
											dialog.dismiss();
										}
									});
							dialog.show();
						} else if (actionId == ID_INFO) {
							itemTemp = blackListItem.get(position);
							Intent intent = new Intent(activity,
									ActivityContactProfile.class);
							Bundle bundle = new Bundle();
							bundle.putSerializable("item", itemTemp);
							intent.putExtra("bundle", bundle);
							activity.startActivity(intent);
							activity.finish();
						} else if (actionId == ID_DELETE) {

							itemTemp = blackListItem.get(position);
							Log.i("TAG XOA", "xoa id: " + itemTemp.getId()
									+ "position: " + position);

							AlertDialog.Builder b = new AlertDialog.Builder(
									activity);
							b.setTitle(activity.getResources().getString(
									R.string.title_alert_dialog1));
							b.setMessage(activity.getResources().getString(
									R.string.message_alert_dialog3));

							b.setNegativeButton("Cancel",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub
											dialog.cancel();
										}
									});

							b.setPositiveButton("OK",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub
											db.deleteBlackListItem(
													BlackListItem.ID + " = "
															+ itemTemp.getId(),
													null);
											blackListItem.remove(position);
											AdapterBlackList.this
													.notifyDataSetChanged();
											Toast.makeText(
													activity,
													activity.getResources()
															.getString(
																	R.string.message_toast_delete),
													Toast.LENGTH_SHORT).show();
										}
									});

							b.show();
						}
					}
				});
		mQuickAction.show(v);
	}

	static class ViewHolder {
		ImageView imgCallMode;
		ImageView img;
		TextView tvName;
		TextView tvPhoneNumber;
	}

	/**
	 * 
	 * @param title
	 * @param message
	 * @param numberPhone
	 * @param what
	 *            1 : callBack, 2 openACtivityChat, 3 delete ITem
	 */
	public void showAlertDialog(String title, String message,
			String numberPhone, final int what) {
		AlertDialog.Builder b = new AlertDialog.Builder(activity);
		b.setTitle(title);
		b.setMessage(message);

		b.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
		});

		b.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				if (what == 1) {
					CallBack();

				} else if (what == 2) {
					openChatActivity();
				} else {

				}

			}
		});

		b.show();
	}

	/**
	 * method open ActivityChat - have add phonenumber and name of this item
	 */
	public void openChatActivity() {

		Intent i = new Intent(activity, ActivityChat.class);
		i.putExtra("phonenumber", item.getPhoneNumber());
		i.putExtra("name", item.getName());
		activity.startActivity(i);
		activity.finish();
	}

	/**
	 * method to recall number of BlackListItem current
	 */
	public void CallBack() {
		Intent callIntent = new Intent(Intent.ACTION_CALL);
		callIntent.setData(Uri.parse("tel:" + item.getPhoneNumber()));
		activity.startActivity(callIntent);
	}

}
